<?php
class ModuleController
{
	private static $modules = array();
	
	public static function loadModule($aModuleName)
	{
		if (self::hasModule($aModuleName))
		{
			Debug::log("Module " . $aModuleName . " has already been loaded", Debug::WARNING);
		}
		else
		{
			Debug::log("Loading module " . $aModuleName, Debug::INFO);
			
			$module = new Module($aModuleName);
			$module->startLoadProgress();
			
			if ($module->function != null)
			{
				self::$modules[] = $module;
				Debug::log("Succesfully loaded module " . $aModuleName . ", now initializing", Debug::INFO);
				$module->initialize();
			}
			else
			{
				Debug::log("Failed to load module " . $aModuleName, Debug::ERROR);
			}
		}
	}
	
	public static function getModule($aModuleName)
	{
		if (!self::hasModule($aModuleName))
			self::loadModule($aModuleName);
			
		foreach (self::$modules as $module)
		{
			if ($module->name == $aModuleName)
				return $module;
		}

		return null;
	}
	
	public static function hasModule($aModuleName)
	{
		foreach (self::$modules as $module)
		{
			if ($module->name == $aModuleName)
				return true;
		}
		
		return false;
	}
	
	public static function reloadModule($aModuleName)
	{
		if (!self::hasModule($aModuleName)) return;
		
		self::unloadModule($aModuleName);
		self::loadModule($aModuleName);
	}
	
	public static function unloadModule($aModuleName)
	{
		for ($i = 0; $i < count(self::$modules); $i++)
		{
			if (isset($modules[$i]) && self::$modules[$i]->name == $aModuleName)
			{
				self::$modules[$i]->run(new Event(Module::UNLOAD_MODULE));
				unset(self::$modules[$i]);
				Debug::log("Succesfully unloaded module " . $aModuleName, Debug::INFO);
			}
		}
	}
	
	public static function unloadAllModules()
	{
		Debug::log("Unloading modules", Debug::INFO);
		array_reverse(self::$modules);
		foreach (self::$modules as $module)
		{
			self::unloadModule($module->name);
		}
	}
}
?>